package hibernate;

import hibernate.entities.Piece;
import hibernate.entities.User;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

public class UserDAO {
	static UserDAO instance = null;
	EntityManager em;
	EntityManagerFactory emf;
	
	public static UserDAO getInstance(EntityManagerFactory emf){
		if (instance == null){
			instance = new UserDAO(emf);
		}
		return instance;
	}
	
	private UserDAO(EntityManagerFactory emf){
		this.emf = emf;
		em = emf.createEntityManager();
	}
	
	public void create(String identifiant, String nom, int taille, char sexe, int humeur, boolean connecte, Piece piece){
		em.getTransaction().begin();
		User u = new User(identifiant, nom, taille, sexe, humeur, connecte, piece);
		em.persist(u);
		em.getTransaction().commit();
	}
	
	public User getUser(int id){
		return em.find(User.class, id);
	}
	
	public void updateHumeur(int id, int humeur){
		em.getTransaction().begin();
		User u = em.find(User.class, id);
		u.setHumeur(humeur);
		em.merge(u);
		em.getTransaction().commit();
	}

	public void updateConnexion(int id, boolean isConnected){
		em.getTransaction().begin();
		User u = em.find(User.class, id);
		u.setConnecte(isConnected);
		em.merge(u);
		em.getTransaction().commit();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers(){
		em.clear();
	    Query query = em.createQuery("SELECT e FROM User e");
	    return (List<User>) query.getResultList();
	}
	
	public void updatePiece(int userId, int pieceId){
		em.getTransaction().begin();
		User u = em.find(User.class, userId);
		Piece p = em.find(Piece.class, pieceId);
		u.setPiece(p);
		em.merge(u);
		em.getTransaction().commit();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUsersOfPiece(Piece piece){
		Query query = em.createQuery("SELECT e FROM User e WHERE piece = ?");
		query.setParameter(1, piece);
		return (List<User>)query.getResultList();
	}
	
}

